<template>
  <div class="page_div">
    <span id="firstPage" @click="firstPage">{{firstPageName}}</span>
    <a id='prePage' @click="prePage">
      <i class='iconfont icon-left'></i>
    </a>
    <a v-for="item in pages" :class="{current:item === current}" :key="item" @click="pageClick(item)" v-if="Number(item)">{{item}}</a>
    <span v-else>{{item}}</span>
    <a id='nextPage' @click="nextPage">
      <i class='iconfont icon-right'></i>
    </a>
    <span id="lastPage" @click="lastPage">{{lastPageName}}</span>
  </div>
</template>


<script>
import "./iconfont.css"
import "./paging.css"
export default {
  props: {
    pageNow: {
      type: Number,
      default: 1
    },
    totalPage: {
      type: Number,
      default: 0
    },
    firstPageName: {
      type: String,
      default: "首页"
    },
    lastPageName: {
      type: String,
      default: "尾页"
    }
  },
  data() {
    return {
      current: this.pageNow
    }
  },
  computed: {
    pages() {
      let array = []
      if (this.total > 6) {
        //当前页数小于5时显示省略号
        if (this.current < 5) {
          for (let i = 1; i < 6; i++) {
            array.push(i)
          }
          array.push("...")
          array.push(this.total)
        } else {
          //页码在中间部分时候
          if (this.current < this.total - 3) {
            for (let i = this.current - 2; i < this.current + 3; i++) {
              array.push(i)
            }
            array.push("...")
            array.push(this.total)
            //判断页码在末尾的时候
          } else {
            array.push(1)
            array.push("...")
            for (let i = this.total - 4; i < this.total + 1; i++) {
              array.push(i)
            }
          }
        }
        //页面总数小于6的时候
      } else {
        for (var i = 1; i < this.total + 1; i++) {
          array.push(i)
        }
      }
      return array
    },
    total() {
      return this.totalPage
    }
  },
  methods: {
    pageClick(item) {
      if (item === this.current) return
      this.current = item
      this._$emit(this.current)
    },
    firstPage() {
      if (this.current === 1) return
      this.current = 1
      this._$emit(this.current)
    },
    lastPage() {
      if (this.current === this.total) return
      this.current = this.total
      this._$emit(this.current)
    },
    prePage() {
      if (this.current - 1 <= 0) return
      this.current -= 1
      this._$emit(this.current)
    },
    nextPage() {
      if (this.current + 1 > this.total) return
      this.current += 1
      this._$emit(this.current)
    },
    _$emit(page) {
      this.$emit("change-page", page)
    }
  },
  created() {
    document.documentElement.onselectstart = e => false
  }
}
</script>
